package cn.javase.concurrent._并发编程._03_Java线程._创建和运行线程;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import org.junit.jupiter.api.Test;

public class _创建和运行线程 {

    // 方法一：直接使用Thread
    @Test
    public void test() {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                System.out.println("123");
            }
        };
        t1.start();
    }

    // 方法二：使用Runnable配合Thread
    @Test
    public void test2() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("456");
            }
        };
        Thread t = new Thread(runnable);
        t.start();
    }

    /*
        小结：方法1是把线程和任务合并在了一起，方法2是把线程和任务分开了
        用Runnable更容易与线程池等高级API配合
        用Runnable让任务类脱离了Thread继承体系，更灵活
     */

    // 方法三：FutureTask配合Thread
    @Test
    public void test3() throws ExecutionException, InterruptedException {
        FutureTask<Integer> task = new FutureTask<>(() -> {
            System.out.println("789");
            Thread.sleep(2000);
            return 100;
        });
        new Thread(task).start();
        // 主线程阻塞，同步等待task执行完毕的结果
        Integer res = task.get();
        System.out.println(res);
    }

}
